import React, { useRef, useEffect, useState } from 'react';
import styles from './DynamicTable.module.less';
import { getReservationListAPI } from '@/api/reservation.api';
import dayjs from 'dayjs';

const ROW_HEIGHT = 51.5;
const PAGE_SIZE = 5;
const HEADER_HEIGHT = 51.5;

const statusColorMap: Record<string, React.ReactNode> = {
  approved: <span style={{ color: '#52c41a' }}>已同意</span>,
  pending: <span style={{ color: '#faad14' }}>待审批</span>,
  rejected: <span style={{ color: '#f5222d' }}>已拒绝</span>,
};

interface ReservationData {
  id: number;
  studentId: string;
  startTime: string;
  endTime: string;
  status: string;
  purpose: string;
  room: {
    roomNumber: string;
    floor: {
      floorNumber: string;
    };
  };
  user: {
    name: string;
    studentId: string;
  };
}

const DynamicTable: React.FC = () => {
  const [reservationList, setReservationList] = useState<ReservationData[]>([]);
  const [offset, setOffset] = useState(0);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    getReservationListAPI().then(res => {
      if (res.data?.data?.list) {
        setReservationList(res.data.data.list);
      }
    });
  }, []);

  // 拼接一份数据用于无缝滚动
  const data = reservationList.length > 0
    ? [...reservationList, ...reservationList.slice(0, PAGE_SIZE)]
    : [];
  const total = reservationList.length;

  // 持续平滑滚动动画
  useEffect(() => {
    if (total <= PAGE_SIZE) return;
    let frame: number;
    let last = Date.now();
    const speed = 20; // px/秒
    const step = () => {
      if (paused) {
        frame = requestAnimationFrame(step);
        return;
      }
      const now = Date.now();
      const delta = now - last;
      last = now;
      setOffset(prev => {
        let next = prev + (speed * delta) / 1000;
        const maxOffset = ROW_HEIGHT * total;
        if (next >= maxOffset) {
          return next - maxOffset;
        }
        return next;
      });
      frame = requestAnimationFrame(step);
    };
    frame = requestAnimationFrame(step);
    return () => cancelAnimationFrame(frame);
  }, [total, paused]);

  const formatDate = (dateString: string) => {
    return dayjs(dateString).format('YYYY-MM-DD');
  };

  const renderCustomHeader = () => (
    <div className={styles['dynamic-table-header']}>
      <div className={styles['cell-floor'] + ' ' + styles['dynamic-table-cell']}>楼层</div>
      <div className={styles['cell-room'] + ' ' + styles['dynamic-table-cell']}>包间号</div>
      <div className={styles['cell-name'] + ' ' + styles['dynamic-table-cell']}>申请人</div>
      <div className={styles['cell-id'] + ' ' + styles['dynamic-table-cell']}>学号</div>
      <div className={styles['cell-start'] + ' ' + styles['dynamic-table-cell']}>开始时间</div>
      <div className={styles['cell-end'] + ' ' + styles['dynamic-table-cell']}>结束时间</div>
      <div className={styles['cell-status'] + ' ' + styles['dynamic-table-cell']}>状态</div>
    </div>
  );

  const renderTableBody = () => (
    <div
      className={styles['dynamic-table-rows']}
      style={{
        transform: `translateY(-${offset}px)`,
        transition: 'none',
        willChange: 'transform',
      }}
      ref={wrapperRef}
    >
      {data.map((row, idx) => (
        <div
          key={idx}
          className={
            styles['dynamic-table-row'] + ' ' +
            (idx % 2 === 0 ? styles['even'] : styles['odd'])
          }
        >
          <div className={styles['cell-floor'] + ' ' + styles['dynamic-table-cell']}>
            {row.room.floor.floorNumber}
          </div>
          <div className={styles['cell-room'] + ' ' + styles['dynamic-table-cell']}>
            {row.room.roomNumber}
          </div>
          <div className={styles['cell-name'] + ' ' + styles['dynamic-table-cell']}>
            {row.user.name}
          </div>
          <div className={styles['cell-id'] + ' ' + styles['dynamic-table-cell']}>
            {row.user.studentId}
          </div>
          <div className={styles['cell-start'] + ' ' + styles['dynamic-table-cell']}>
            {formatDate(row.startTime)}
          </div>
          <div className={styles['cell-end'] + ' ' + styles['dynamic-table-cell']}>
            {formatDate(row.endTime)}
          </div>
          <div className={styles['cell-status'] + ' ' + styles['dynamic-table-cell']}>
            {statusColorMap[row.status] || row.status}
          </div>
        </div>
      ))}
    </div>
  );

  return (
    <div
      className={styles['dynamic-table-wrapper']}
      style={{
        height: ROW_HEIGHT * PAGE_SIZE + HEADER_HEIGHT,
        position: 'relative',
        top: -15,
      }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {renderCustomHeader()}
      <div className={styles['dynamic-table-body']} style={{ height: ROW_HEIGHT * PAGE_SIZE }}>
        {renderTableBody()}
      </div>
    </div>
  );
};

export default DynamicTable; 